//
//  SEGActivityOffLineViewController.m
//  ExcellentHome
//
//  Created by 揭婧雯 on 2017/8/11.
//  Copyright © 2017年 陈区. All rights reserved.
//
// 线下类

#import "SEGActivityOffLineViewController.h"
#import "SEGActivityDetailUsersCell.h"
#import "SEGActivityOffLineInfoCell.h"

@interface SEGActivityOffLineViewController ()
/**
 剩余名额
 */
@property (nonatomic, copy)NSString *perCount;
@property (nonatomic, strong) SEGActivityOffLineInfoCell *infoCell; ///< 缓存info cell，防止滚动到底部时获取不到cell
@end

@implementation SEGActivityOffLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 重置展示数据
    self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_JoinedUser),  @(SEGActivityDetailCellDispalyType_Comment)];
    
    self.perCount = @"0";
    [self.tableView registerClass:[SEGActivityDetailUsersCell class] forCellReuseIdentifier:kActivityDetailUsersCellIdentifier];
    [self.tableView registerClass:[SEGActivityOffLineInfoCell class] forCellReuseIdentifier:kActivityOffLineInfoCellIdentifier];
    
    //监听键盘事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - 根据不同类型活动进行界面设置 子类根据需要重写
/// 请求详情后请求其他数据
- (void)requestOtherInfoAfterDetail {
    //请求线下类 剩余名额和报名审核状态
    [self.detailViewModel.requestOfflineStatusSignal subscribeNext:^(id  _Nullable x) {
        RACTupleUnpack(NSNumber *applyAuditStatusNumber, NSString *perCount) = x;
        SEGActivityApplyAuditStatus applyStatus = [applyAuditStatusNumber integerValue];
        [self.toolBarView changePublicButtonByApplyAuditStatus:applyStatus];
        self.perCount = perCount;
        if ([self.perCount intValue] <= 0) {//如果剩余名额为0，按钮的文案显示为“报名结束”
            [self.toolBarView changePublicButtonByApplyAuditStatus:SEGActivityApplyAuditStatus_TimeOver];
        }
        
        //不能报名时不现实不填写界面
        if (applyStatus != SEGActivityApplyAuditStatus_CanApply) {
            // 重置展示数据
            self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_JoinedUser),  @(SEGActivityDetailCellDispalyType_Comment)];
            
        }else {
            // 重置展示数据
            self.displayTypeArray = @[@(SEGActivityDetailCellDispalyType_Rule), @(SEGActivityDetailCellDispalyType_TencentAD), @(SEGActivityDetailCellDispalyType_JoinedUser), @(SEGActivityDetailCellDispalyType_OfflineSignUp),  @(SEGActivityDetailCellDispalyType_Comment)];
        }
        [self.tableView reloadData];
        
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

/// 返回section中的行数
- (NSInteger)setRowsInSection:(NSInteger)section {
    return 1;
}

/// 返回cell
- (UITableViewCell *)setCellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGActivityDetailCellDispalyType displayType = [self.displayTypeArray[indexPath.section] integerValue];
    if (displayType == SEGActivityDetailCellDispalyType_JoinedUser) {//参加人数
        SEGActivityDetailUsersCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kActivityDetailUsersCellIdentifier forIndexPath:indexPath];
        [cell setUpCellWithModel:self.detailModel isOffLine:YES];
        [cell setPerCount:self.perCount];
        return cell;
    }
    if (displayType == SEGActivityDetailCellDispalyType_OfflineSignUp) {
        SEGActivityOffLineInfoCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kActivityOffLineInfoCellIdentifier forIndexPath:indexPath];
        self.infoCell = cell;
        return cell;
    }
    return [UITableViewCell new];
}

/// 设置cell高度
- (CGFloat)setHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2) {//参加人数
        return UITableViewAutomaticDimension;
    } else {
        return 268;
    }
}

#pragma mark 键盘弹出
- (void)keyboardWillShowChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    if (![self.commentInputView.inputBarView.textView isFirstResponder]) {
        [self keyboardWillShowChangeHeight:kbSize.height duration:duration];
    }
}

- (void)keyboardWillHideChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    if (![self.commentInputView.inputBarView.textView isFirstResponder]) {
        [self keyboardWillHiddenChangeHeight:kbSize.height duration:duration];
    }
}

- (void)keyboardWillShowChangeHeight:(CGFloat)height duration:(CGFloat)duration {
    [UIView animateWithDuration:duration animations:^{
        self.tableView.transform = CGAffineTransformMakeTranslation(0, -(height - activityToolBarNormalHeight));
    }];
}

- (void)keyboardWillHiddenChangeHeight:(CGFloat)height duration:(CGFloat)duration {
    [UIView animateWithDuration:duration animations:^{
        self.tableView.transform = CGAffineTransformIdentity;
    }];
}

#pragma mark - SEGActivityDetailToolBarDelegate
- (void)applyButtonAction {
    // 组装数据
    SEGActivityOffLineInfoCell *cell = self.infoCell;
    NSString *name = cell.nameField.text;
    NSString *sex = cell.maleButton.selected ? @"1" : @"2";
    NSString *tel = cell.phoneField.text;
    NSString *applyCount = cell.numberField.text;
    NSString *remark = cell.remarkView.text;
    // 执行command
    [[self.detailViewModel.joinOfflineActivityCommand execute:RACTuplePack(name, sex, tel, applyCount, remark)] subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD show];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error.code == kActicityErrorCode_NoAuth) {
            [self showNothAlterView];
            return;
        }
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    } completed:^{
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:@"报名成功"];
        [self headerRereshing]; //刷新页面
    }];
}

@end
